using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Baula.Testing.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Baula.TextGen.ActiveTemplating.Tests
{
    [TestClass]
    public class TableInfoTests
    {
        [TestMethod]
        public void FieldNames_SetOnNonEmptyFieldList_ThrowsException()
        {
            var table = new TableInfo();
            table.Fields.Add(new FieldInfo("Some field"));
            var exception = ExceptionAssert.Expect(
                () => table.FieldNames = "Something");
            Assert.AreEqual("FieldNames is readonly if there are already any fields assigned to the table.", exception.Message);
        }

        [TestMethod]
        public void FieldNames_SetToEmptyString_GivesNoFields()
        {
            var table = new TableInfo {FieldNames = string.Empty};
            Assert.AreEqual(0, table.Fields.Count);
        }

        [TestMethod]
        public void FieldNames_SetToSingleFieldName_GivesThisSingleField()
        {
            var table = new TableInfo {FieldNames = "TheField"};
            Assert.AreEqual(1, table.Fields.Count);
            Assert.AreEqual("TheField", table.Fields[0].Name);
        }

        [TestMethod]
        public void FieldNames_SetToMultipleFieldsWithSpaces_GivesTheFieldsWithTrimmedNames()
        {
            var table = new TableInfo {FieldNames = " Field 1, Field 2 , Field 3 "};
            Assert.AreEqual(3, table.Fields.Count);
            AssertFieldNames(table, "Field 1", "Field 2", "Field 3");
        }

        private void AssertFieldNames(TableInfo table, params string[] fieldNames)
        {
            var expectedFields = fieldNames
                .Select(fieldName => new FieldInfo(fieldName))
                .Cast<IFieldInfo>().ToList();
            CollectionAssert.AreEqual(expectedFields, (ICollection) table.Fields);
        }
    }
}